/*
 * Copyright 2012-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.diagnostics;

import org.springframework.core.ResolvableType;

/**
 * 大多数 {@code FailureAnalyzer} 实现的抽象基类。
 *
 * @param <T> 要分析的异常类型
 * @author Andy Wilkinson
 * @author Phillip Webb
 * @since 1.4.0
 */
public abstract class AbstractFailureAnalyzer<T extends Throwable> implements FailureAnalyzer {

	@Override
	public FailureAnalysis analyze(Throwable failure) {
		// 🔍查找指定类型的根本原因（Cause）
		T cause = findCause(failure, getCauseType());

		// ✅如果找到原因，则进行分析，否则返回 null
		return (cause != null) ? analyze(failure, cause) : null;
	}

	/**
	 * 返回对给定 {@code rootFailure} 的分析，如果无法分析则返回 {@code null}。
	 * @param rootFailure 传递给分析器的根本故障
	 * @param cause 实际发现的原因
	 * @return 分析结果，或 {@code null}
	 */
	protected abstract FailureAnalysis analyze(Throwable rootFailure, T cause);

	/**
	 * 返回分析器处理的故障类型。默认使用类泛型。
	 * @return 故障类型
	 */
	@SuppressWarnings("unchecked")
	protected Class<? extends T> getCauseType() {
		return (Class<? extends T>) ResolvableType.forClass(AbstractFailureAnalyzer.class, getClass()).resolveGeneric();
	}

	@SuppressWarnings("unchecked")
	protected final <E extends Throwable> E findCause(Throwable failure, Class<E> type) {
		// 🔄 循环遍历异常链，直到末尾
		while (failure != null) {
			// ✔️ 判断当前异常是否属于指定类型
			if (type.isInstance(failure)) {
				// 🎯 找到目标类型异常，强制转换后返回
				return (E) failure;
			}
			// ↪️ 获取当前异常的原因，继续循环查找
			failure = failure.getCause();
		}
		// ❌ 未找到指定类型异常，返回 null
		return null;
	}

}
